package com.company;

import javax.swing.*;
import java.awt.*;
import java.util.Random;

public class Plansza extends JPanel {
	private MainWindow mw;
	private Pole[][] pola;
	private int n;
	private int liczbaMin;

	public Plansza( MainWindow mw, int n, int liczbaMin ) {
		this.n = n;
		this.liczbaMin = liczbaMin;
		this.mw = mw;
	}

	public void initializeNewGame() {
		Component[] components = this.getComponents();
		for ( Component component : components ) {
			if ( component.getClass().getSimpleName().equalsIgnoreCase( "JButton" )) this.remove( component );   						// usuwa z panelu wszystkie obiekty typu JButton
		}
		pola = new Pole[n][n];

		this.setLayout( new GridLayout( n, n ) );
		for ( int i = 0; i < n; i++ ) {
			for ( int j = 0; j < n; j++ ) {
				Pole p = new Pole( i, j, this );
				pola[i][j] = p;
				this.add( p.getButton() );
			}
		}
		placeMines();
		this.revalidate();
		this.repaint();
	}

	public MainWindow getMainWindow() {
		return this.mw;
	}

	void placeMines() {
		int m = 0;
		Random r = new Random();
		while ( m < liczbaMin ) {
			int i, j;
			i = r.nextInt( n );
			j = r.nextInt( n );

			if ( !pola[i][j].isMine() ) {
				pola[i][j].setMine( true );
				m++;
			}
		}
	}

	public boolean isMine( int i, int j ) {
		if ( (i >= 0) && (i < n) && (j >= 0) && (j < n) ) {
			return pola[i][j].isMine();
		}
		return false;
	}

	public void openAll() {                                      //pokazanie wszystkich pol, ustawienie znacznika min i zablokowanie aktywnosci
		for ( Pole[] fields : pola ) {
			for ( Pole field : fields ) {
				String text = "";
				if ( field.isMine() ) {
					text = "M";
				} else {
					int mineCount = field.mineCount();
					if ( mineCount > 0 ) {
						text = Integer.toString( mineCount );
					}
				}
				field.getButton().setText( text );
			}
		}
	}

	public Pole getFieldAtIndex( int x, int y ) {
		return pola[x][y];
	}

	public MainWindow getMw() {
		return mw;
	}

	public void setMw( MainWindow mw ) {
		this.mw = mw;
	}

	public Pole[][] getPola() {
		return pola;
	}

	public void setPola( Pole[][] pola ) {
		this.pola = pola;
	}

	public int getN() {
		return n;
	}

	public void setN( int n ) {
		this.n = n;
	}

	public int getLiczbaMin() {
		return liczbaMin;
	}

	public void setLiczbaMin( int liczbaMin ) {
		this.liczbaMin = liczbaMin;
	}
}
